package com.zeen.wima.common;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.util.Log;


public class HttpRequest implements Runnable {

	private String url = "";
	private HttpCallback _callback;
	public static final String XDEBUG_SESSION = "X=0"; //XDEBUG_SESSION_START=ECLIPSE_DBGP&KEY=12880732597961
	static final String ERR = "error";

	public HttpRequest() {
		
	}

	public void send(String url, String cmd, ArrayList<NameValuePair> params,String sessionId,HttpCallback callback) {
		_callback = callback;
		String qurey = "?cmd=" + cmd;
		Iterator<NameValuePair> i = params.iterator();
		while (i.hasNext()) {
			NameValuePair nv = (NameValuePair) (i.next());
			qurey += "&" + nv.getName() + "="
					+ URLEncoder.encode(nv.getValue());
		}
		this.url = url + qurey;
		// session
		this.url += "&sessionId=" + sessionId;
		// debug session
		if (!XDEBUG_SESSION.equals("")) {
			this.url += "&" + XDEBUG_SESSION;
		}
		//Log.i("http", this.url);
		new Thread(this).start();
	}

	@Override
	public void run() {
		HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, 15 * 1000);
		HttpConnectionParams.setSoTimeout(httpParameters, 30 * 1000);
		HttpClient client = new DefaultHttpClient(httpParameters);
		client.getParams().setParameter(
				HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8");
		HttpGet httpRequest = new HttpGet(url);
		Log.i("http", url);
		String rStr = "";
		try {
			HttpResponse httpResponse = client.execute(httpRequest);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
			    rStr = EntityUtils.toString(httpResponse.getEntity());
				Log.i("http", rStr);
				JSONObject response = new JSONObject(rStr);
				if (_callback != null) {
					_callback.onResponse(response.getString("code"), response
							.getString("msg"), response.getJSONArray("data"));
				}
			} else {

			}
		} catch (Exception e) {
			Log.e("DataRequest", " response:" + rStr);
		} finally {
			
		}
	}

}
